package com.ifar.audiosdk.utils

import android.os.Handler
import com.ifar.audiosdk.common.IfarVideoConfig
import io.agora.rtc.mediaio.IVideoFrameConsumer
import io.agora.rtc.mediaio.IVideoSource
import io.agora.rtc.video.AgoraVideoFrame

class IfarVideoSource : IVideoSource {
    private val whatPushFrame = 1   //推流消息标记
    private var isSourceStart = false
    private var actionTime = 1000 / 30
    private var handler = Handler {
        when (it.what) {
            whatPushFrame -> pushFrame()
        }
        false
    }

    private fun pushFrame() {
        handler.post(getFrame)
        handler.sendEmptyMessageDelayed(whatPushFrame, actionTime.toLong())
    }

    private var videoConsumer: IVideoFrameConsumer? = null
    private var getFrame = Runnable {
        if (GlassHandle.frame != null) {
            videoConsumer?.consumeByteArrayFrame(GlassHandle.frame,
                AgoraVideoFrame.FORMAT_NV21,
                IfarVideoConfig.resolutionW,
                IfarVideoConfig.resolutionH,
                0,
                System.currentTimeMillis())
        }
    }

//    suspend fun frameHandle(){
//        withContext(Dispatchers.IO){
//
//        }
//    }

    override fun onInitialize(consumer: IVideoFrameConsumer?): Boolean {
        videoConsumer = consumer
        return true
    }

    override fun onStart(): Boolean {
        isSourceStart = true
        handler.sendEmptyMessage(whatPushFrame)
        return isSourceStart
    }

    override fun onStop() {
        isSourceStart = false
        handler.removeMessages(whatPushFrame)
        handler.removeCallbacks(getFrame)
    }

    override fun onDispose() {}

    override fun getBufferType(): Int {
        return AgoraVideoFrame.BUFFER_TYPE_ARRAY
    }
}